'use strict';

/* Controllers */
/**
 * 这个js主要是angularjs的mvc框架的controller
 */
angular.module('myApp.controllers', ['myApp.CacheServices','myApp.IMServices','myApp.MessageHandler','myApp.MessageView','myApp.ChatHandler','myApp.ChatModel','myApp.GroupHandler', 'myApp.ContactHandler', 'myApp.FileHandler', 'chieffancypants.loadingBar']).
	controller('bodyController', ['$scope','$rootScope','LocalCacheService','IMService','$filter','MessageHandler','MessageView', 'ChatHandler','Chat','GroupHandler', 'ContactHandler', 'FileHandler', '$q','$timeout',
        function ($scope, $rootScope,LocalCacheService,IMService,$filter,MessageHandler,MessageView,ChatHandler,Chat, GroupHandler, ContactHandler, FileHandler, $timeout) {
		//显示或者关闭用户设置界面，阻止事件冒泡
		$scope.changeOperaterListStatu = function($event){
			$('iframe[name="feedbackIframe"]')[0].src=window.feedbackAddress;
			$scope.showOperaterList=!$scope.showOperaterList;
			util.supported();
			$event.stopPropagation();
			return false;
		};
        //点击切换声音控制，阻止事件冒泡
		$scope.changeVoiceStatu = function($event){
			$rootScope.voiceStatu ? LocalCacheService.del('voiceStatu') : LocalCacheService.set('voiceStatu', 1);
			$rootScope.voiceStatu = !$rootScope.voiceStatu;
			$event.stopPropagation();
			return false;
		};
		//桌面通知
		$scope.changeNotification = function($event){
            $rootScope.notification ? LocalCacheService.del('notification') : LocalCacheService.set('notification', 1);
			window.Notification.requestPermission();
			$rootScope.notification = !$rootScope.notification;
			setTimeout(function(){if(window.Notification.permission != 'granted'){$rootScope.notification=false;}}, 5000);
            $event.stopPropagation();
            return false;
		};
		//点击意见反馈
		$scope.doFeedBack = function($event){
			//初始化frame
			$scope.showMaskBox = true;
			$scope.showFeedbackBox = true;
		};
		//关闭意见反馈
		$scope.closeFeedBack = function($event){
			//初始化frame
            $scope.showMaskBox = false;
			$scope.showFeedbackBox = false;
			$('iframe[name="feedbackIframe"]')[0].src=window.feedbackAddress;
		};
		//点击退出
		$scope.doQuitBack = function($event){
            $scope.showMaskBox = true;
			$scope.showQuitBox = true;
		};
		//确定退出
		$scope.doLogout = function($event){
            $scope.showMaskBox = false;
			$scope.showQuitBox = false;
			IMService.quit(function(){
				window.location = 'login.do';
			});
		};
        $rootScope.safeApply = function (fn) {
            var phase = this.$root.$$phase;
            if (phase == '$apply' || phase == '$digest') {
                if (fn && (typeof(fn) === 'function')) {
                     fn();
                 }
             } else {
                    this.$apply(fn);
             }
         };
		$rootScope.showMute = false;
		//初始化一些变量
		$rootScope.currentChatObj = null;
        //遮盖层
        $rootScope.showMaskBox = true;
        //消息反馈box
		$scope.showFeedbackBox = false;
		//退出box
		$scope.showQuitBox = false;
		//保存文件名集合
		$scope.fileNameList = {};
		$scope.content='';
		
		//控制聊天确认界面的显示
		$scope.showConfrimChatBox = false;
		//控制消息盒子的显示
		$scope.showMessageBox = false;
		//控制显示添加群成员面板
		$scope.showAddParticipantsBox = false;
		//控制修改图像界面的显示
		$scope.showModifyAvatar = false;
		//存放所有的message
		//$scope.allMessage = {};
		//转换html实体
		$scope.showText=true;
		//不过滤html标签
		$scope.showHtml=false;
		
        //取消个人聊天
		$scope.hideChatBox = function(){
			$scope.confirmChatObj = null;
			$scope.showMaskBox = false;
			$scope.showConfrimChatBox = false;
		};

        $scope.editAvatar = function(){
            if(!$rootScope.user.tempAvatar){
                $rootScope.user.tempAvatar = $rootScope.user.avatar;
            }
        }
        //关闭添加联系人窗口
        $scope.closeAddContactBox = function(){
            $scope.showAddGroupContactBox=false;
            $scope.showAddParticipantsBox=false;
            $scope.showMaskBox=false;
            $scope.groupCondition='';
            $scope.groupPersons=[];
        }
        
        $scope.resetChatBoxStyle = function(type){
        	if(type == 1 && !$scope.searchCondition){//重置
        		$('div#mainListContainer').css('overflow-y','hidden');
        	}else{//还原
        		$('div#mainListContainer').css('overflow-y','scroll');
        	}
        };
        
        $('#btnUploadUserAvatar').click(function(){
            $('#uploadUserAvatar').trigger('click');
        });
		//定义选择图片时间
		$('#uploadUserAvatar').on('change', function() {
            if (this.files.length != 0 ) {
				var file = this.files[0];
                $scope.preUploadUserAvatar(file);
			}
		});

        $scope.preUploadUserAvatar = function(file){
            if(!/image\/\w+/.test(file.type)){
                swal({title : '请确保文件为图像类型！', timer : 2000, showConfirmButton : false});
                return;
            }
            var reader = new FileReader();
            if (!reader){
                swal({title : '浏览器不支持FileReader！', timer : 2000, showConfirmButton : false});
                return;
            }
            reader.onloadend = function(e) {
                //读取成功，显示到页面
                $rootScope.$apply(function(){
                    $rootScope.user.tempAvatar = e.target.result;
                });
            };
            reader.readAsDataURL(file);
        }

        //保存头像
        $scope.updateUserAvatar = function () {
            $scope.showLoad =  true;
            $.post('contact/uploadUserAvatar.do',
                   {avatar: $rootScope.user.tempAvatar},
                   function (data) {
                       if(util.tokenIsExpired(data)){//检查TOKEN是否过期
                           util.tokenExpire();
                           return;
                       }
                       if (data.error) {
                           swal({title : data.error, timer : 2000, showConfirmButton : false});
                           return;
                       }
                       $scope.$apply(function () {
                           $scope.showModifyAvatar = false;
                           $scope.showImageEdit = false;
                           $scope.showMaskBox = false;
                           $rootScope.user.avatar = $rootScope.user.tempAvatar;
                           $scope.showLoad = false;
                           //清空file
                           var file = $('#uploadUserAvatar');
                           file.after(file.clone().val(''));
                           file.remove();
                           $('#uploadUserAvatar').on('change', function () {
                               if (this.files.length != 0) {
                                   var file = this.files[0];
                                   $scope.preUploadUserAvatar(file);
                               }
                           });
                           if ($rootScope.user.tempAvatar) $rootScope.user.tempAvatar = null;
                       });
            });
        }

        //点击其他地方隐藏emoji panel
        $(function(){ 
        	$(document).bind('click',function(e){
        	var target = $(e.target);
        	if(target.closest('.emojiPanel').length == 0 && target.closest('#selectfeel').length==0){
        		$scope.showEmoji=false;

        		$scope.$apply();

        		}
        	});
       	});

		$('.bg4').find('a').click(function(){
            var ti=$(this).attr('title');
            $scope.content+=('['+ti+']');
            $scope.showEmoji=false;
		}); 
        $('.bg3').find('a').click(function(){
            var ti=$(this).attr('title');
            $scope.content+=('['+ti+']');
            $scope.showEmoji=false;
		});
        $('.bg2').find('a').click(function(){
            var ti=$(this).attr('title');
            $scope.content+=('['+ti+']');
            $scope.showEmoji=false;
		});
   	  
		//添加或者删除星标联系人
		$scope.changeStar = function(contact){
            var paramData = {'operation' : contact.star?'del':'add', 'username' : contact.identifier};
            ContactHandler.commonlyUsedContacterPromise(paramData).then(function(data){
                if(contact.star){
                    $rootScope.starContacts[contact.identifier]=null;
                    $rootScope.usernames.remove(contact.identifier);
                    contact.star=false;
                }else{
                    $rootScope.starContacts[contact.identifier]=contact;
                    $rootScope.usernames.push(contact.identifier);
                    contact.star=true;
                }
            }, function(error){
                swal({title : error, timer : 2000, showConfirmButton : false});
                return;
            });
		};

        //显示人员信息
        $scope.showContactInfo = function (contactIdentifier) {
            var contact = ContactHandler.getContact(contactIdentifier);
            $scope.personChat(contact);
        }

        //点击查询结果
        $scope.clickSearchResultObj = function(searchResultObj) {
            searchResultObj.isGroup ? $scope.groupChat(searchResultObj) : $scope.personChat(searchResultObj);
        }

		//点击个人准备聊天
		$scope.personChat = function(contact){
            //判断是否是星标联系人
            if ($scope.usernames.contains(contact.identifier)) contact.star = true;
            $scope.confirmChatObj = contact;
            $scope.showMaskBox = true;
            $scope.showConfrimChatBox = true;
       
		};

        //点击个人聊天确认按钮
        $scope.confirmChat = function (contact) {
            ChatHandler.addChat(Chat.contactToChat(contact));
            $scope.searchCondition = '';
            $scope.content = '';
            $scope.confirmChatObj = null;
            $rootScope.isGroup = false;
            $scope.showMaskBox = false;
            $scope.showConfrimChatBox = false;
            $scope.showMessageBox = true;
            $rootScope.currentChatObj = contact;
            //初始化成员设置面板
            $('.contactSetupContainer').css('width', '0px');
            //初始化放消息的数组
            MessageView.init(contact.identifier);
            $scope.showAddress = false;
            $scope.searchCondition = '';
            $('textarea.messageInput').focus();
        };
		
		//点击最近聊天记录
		$scope.recentChat = function(chat, event){
			if($scope.content != null && $scope.content.length > 0 && $rootScope.currentChatObj){
				$rootScope.chatsMap[$rootScope.currentChatObj.identifier].unsendMsg = $scope.content;
			}
			$scope.content = '';
            $scope.searchCondition = '';
            $rootScope.isGroup  = chat.isGroup;
            $scope.showMessageBox = true;
            $rootScope.allUnreadMessages -= chat.unreadMessages ;
            chat.unreadMessages=0;
            MessageView.init(chat.identifier);
            $('.contactSetupContainer').css('width', '0px');//初始化成员面板
            if(chat.isGroup){
                $rootScope.currentChatObj = GroupHandler.getGroupByIdentifier(chat.identifier);
            }else{
                $rootScope.currentChatObj = ContactHandler.getContact(chat.identifier);
            }   
            if($rootScope.chatsMap[$rootScope.currentChatObj.identifier].unsendMsg){
            	$scope.content = $rootScope.chatsMap[$rootScope.currentChatObj.identifier].unsendMsg;
            	$rootScope.chatsMap[$rootScope.currentChatObj.identifier].unsendMsg = '';
            }
            //页面中间圆点跟随点击
            $('.associated').animate({'top': util.getClickChatTop(event.target)}, 200);
            $scope._scrollTop = $('#mainListContainer').scrollTop();
            $('textarea.messageInput').focus();
		};

        $('#mainListContainer').scroll(function(){
            setTimeout(function(){
                if($scope._scrollTop == null) return;
                $('.associated').animate({'top': util.getClickChatTop($('.left_chat')[0])}, 200);
            }, 500);
        });
		
		//点击群聊开始聊天
		$scope.groupChat = function(group){
            ChatHandler.addChat(Chat.groupToChat(group));
            $rootScope.isGroup  = true;
			$scope.showMessageBox = true;
			$rootScope.currentChatObj = group;
            $scope.showAddress = false;
            $scope.searchCondition = '';
			//初始化成员设置面板
			$('.contactSetupContainer').css('width', '0px');
            $scope.showAddress = false;
			//初始化放消息的数组
			MessageView.init(group.identifier);
			$('textarea.messageInput').focus();

		};
		
		//点击修改图片
		$scope.updateAvatar = function($event){
			$scope.showMaskBox = true;
			$scope.showModifyAvatar = true;
		};
		//关闭群成员设置
		$scope.hideSetup=function(){
			$('.contactSetupContainer').animate({
		        'width': 0
		    }, 500);
			$('textarea.messageInput').focus();
		};

         //快捷键发送消息
         $scope.shortKeySendMessage = function (event) {
             if (!$scope.showMessageBox || $scope.content == null || $scope.content == '') {
                 return;
             }
             if (event.ctrlKey && event.keyCode == 13) {//ctr + enter
                 $scope.sendMessage();
             }
         }
		//发送消息
		$scope.sendMessage = function(){
            if ($scope.content == null || $scope.content == '') {
                swal({title : '不能发送空消息，请输入内容！', timer : 2000, showConfirmButton : false});
                return;
            }
            var message = MessageHandler.text($rootScope.user.identifier, $rootScope.currentChatObj.identifier, $rootScope.user.avatar, $scope.content);
            message.isme = $rootScope.user.identifier;
            message.group = $rootScope.isGroup;
            ChatHandler.addChat(ChatHandler.message2Chat(message)); //添加聊天对象
            $scope.content = '';//清空聊天内容
            $('textarea.messageInput').focus();
            util.resetChatBox();
        
		};
		$scope.doubleSend = function(message){
			message.sendState = 0;
			$rootScope.chatsMap[message.to].sendState = 0;
			MessageHandler.resend(message);
		};

        $scope.playVoice = function(message){
              playByteArray(message.voiceContent);
//            wsutil.generateAudioUrl()
//            $scope.player = new window.Audio();
//            $scope.player.src = wsutil.generateAudioUrl(message.voiceContent);
//            $scope.player.play();
        }

		//点击聊天成员设置
        $scope.setupContact=function(obj){
            $scope.groupContactIderfiers = [];//群聊人员标识数组
            $rootScope.currentChatObj.isDeptGroup = false;
            if($rootScope.isGroup){
                var group = GroupHandler.getGroupByIdentifier(obj.identifier);
                $scope.groupName = group.name;
                $scope.groupCreator = group.accountUid;
                $scope.currentContacts = [];
                ContactHandler.getContactsByGroupPromise(obj.identifier, true).then(function(contacts){
                    $scope.currentContacts = contacts;
                    angular.forEach(contacts, function(contact){
                            $scope.groupContactIderfiers.push(contact.identifier);
                    });
                }, function(){
                    swal({title : '加载群成员失败，请稍后重试', timer : 2000, showConfirmButton : false});
                    return;
                });
                var deptGroupIdentifiers = GroupHandler.getDeptGroupIdentifiers();
                $rootScope.currentChatObj.isDeptGroup = deptGroupIdentifiers.contains($rootScope.currentChatObj.identifier);
		    }else{
                $scope.groupContactIderfiers.push($rootScope.currentChatObj.identifier);
                $scope.groupContactIderfiers.push($rootScope.user.identifier);
            }
			$('.contactSetupContainer').animate({width:649}, 500);
		};


        //拖拽文件
        $(function(){
            var box = document.getElementById('drop_area'); //拖拽区域
            $scope.showDropArea = false;
            var enterCount = 0;
            $(document).on({
                dragenter: function (e) {    //拖进
                    enterCount++;
                    $scope.safeApply(function(){
                        $scope.showDropArea = true;
                    });
                },
                dragleave: function (e) {    //拖离
                    enterCount--;
                    if(enterCount == 0){
                        $scope.safeApply(function() {
                            $scope.showDropArea = false;
                        });
                    }
                },
                drop: function (e) {    //拖离
                    $scope.safeApply(function () {
                        $scope.showDropArea = false;
                    });
                }
            });
            box.ondrop = function(event) {
                event.preventDefault();
                var fileList = event.dataTransfer.files; //获取文件对象
                //检测是否是拖拽文件到页面的操作
                if (fileList.length == 0) {
                    return false;
                }
                $scope.sendFile(fileList[0]);
                $scope.showDropArea = false;
            }
        });

		$('#selectPic').on('click', function() {
			$('#selectFile').click();
		});
		//下载文件
		$scope.downloadFile = function(url){
			window.frames['Iframe1'].location.href = url;
		};
		
		//定义选择图片时间
		$('#selectFile').on('change', function() {
			if (this.files.length != 0 ) {
				var file = this.files[0];
                $scope.sendFile(file);
            }
		});

        $scope.sendFile = function(file,fileMessage){
            if(file.size == 0 || file.type == ''){
                swal({title : '文件无效，请重新选择', timer : 2000, showConfirmButton : false});
                return;
            }
            if(file.size > 1024 * 1024 * 1024){//1G限制
                swal({title : '上传文件不能超过1G！', timer : 2000, showConfirmButton : false});
                return;
            }

            //清空file input
            var fileElem = $('#selectFile');
            fileElem.after(fileElem.clone().val(''));
            fileElem.remove();
            $('textarea.messageInput').focus();
            $('#selectFile').unbind('change').bind('change', function(){
                if (this.files.length != 0 ) {
                    var file = this.files[0];
                    $scope.sendFile(file);
                }
            })

            //var fileMessage;
            if(util.isimg(file.name)){
            	$rootScope.safeApply(function(){
            		fileMessage = MessageHandler.showImage($rootScope.user.identifier, $rootScope.currentChatObj.identifier, $rootScope.user.avatar,'' , '');
            	});
            	document.getElementById(fileMessage.timestamp+'progressBar').style.display = 'block';
            }else{
            	$rootScope.safeApply(function(){
            		fileMessage=MessageHandler.showFile($rootScope.user.identifier, $rootScope.currentChatObj.identifier, $rootScope.user.avatar, '', '', file.name, file.size);
            	});
            	document.getElementById(fileMessage.timestamp+'progressBar').style.display = 'block';
            }
            //ADD-TODO 暂不处理同名文件进度条问题
//            if($scope.fileNameList[file.name]){
//            	//console.log('文件重名,3秒后继续上传');
//                if(fileNameRepetitionTimeout) clearTimeout(fileNameRepetitionTimeout);
//                setTimeout(function(){$scope.sendFile(file,fileMessage);}, 4000);
//            	return;
//            }
            var reader = new FileReader();
            if (!reader) {
                swal({title : '浏览器不支持FileReader！', timer : 2000, showConfirmButton : false});
                return;
            };
            $scope.fileNameList[file.name] = file;
            reader.onloadend = function (e) {
                var progressInterval = showProgress(fileMessage.timestamp,file.name);
                FileHandler.updateFileForm(file).then(function(data){
                    delete $scope.fileNameList[file.name];
                	switch (data.uploadFileType){
                        case 'IMG' :
                            //MessageHandler.image($rootScope.user.identifier, $rootScope.currentChatObj.identifier, $rootScope.user.avatar,data.thumb , data.mediaId);
                        	fileMessage.thumbContent = data.thumb;
                        	fileMessage.mediaId = data.mediaId;
                        	fileMessage = MessageHandler.sendImage(fileMessage);
                        	fileMessage.isme = $rootScope.user.identifier;
                        	fileMessage.messageTime = util.getServerTime();
                        	fileMessage.identifier = $rootScope.currentChatObj.identifier;
                        	fileMessage.content = '[图片]';
                        	fileMessage.group = $rootScope.isGroup;
                            ChatHandler.addChat(ChatHandler.message2Chat(fileMessage));
                            document.getElementById(fileMessage.timestamp+'progressBar').style.display = 'none';
                            setTimeout(function(){util.chatScorllTop();}, 200);
                            break;
                        case  'FILE' :
                            fileMessage.mediaId = data.mediaId;
                            fileMessage = MessageHandler.sendFile(fileMessage);
                            fileMessage.isme = $rootScope.user.identifier;
                            fileMessage.messageTime = util.getServerTime();
                            fileMessage.identifier = $rootScope.currentChatObj.identifier;
                            fileMessage.content = '[文件]';
                            fileMessage.group = $rootScope.isGroup;
                            ChatHandler.addChat(ChatHandler.message2Chat(fileMessage));
                            document.getElementById(fileMessage.timestamp+'progressBar').style.display = 'none';
                            //MessageHandler.file($rootScope.user.identifier, $rootScope.currentChatObj.identifier, $rootScope.user.avatar, '', data.mediaId, file.name, file.size);
                            break;
                        default :
                            return;
                    }
                }, function(errorMessage){
                    window.clearInterval(progressInterval);
                    swal({title : errorMessage, timer : 2000, showConfirmButton : false});
                    return;
                });
            };
            reader.readAsDataURL(file);
        }
		
		//添加人员聊天多于4个可以左右滚动查看
		$(function(){
			$scope.page = 1;
		    var i = 4; //每版放4个图片
		    //向后 按钮
		    $('div.rbtn').click(function(){    //绑定click事件
			     var $parent = $(this).parents('div.numadd');//根据当前点击元素获取到父元素
				 var $v_show = $parent.find('#adimg'); //匹配UL
				 var $v_content = $parent.find('.addcontactimg'); //匹配UL外围Div
				 var v_width = $v_content.width() ;
				 var len = $v_show.find('li').length; //计算LI个数
				 var page_count = Math.ceil(len / i) ;   //只要不是整数，就往大的方向取最小的整数
				 if( !$v_show.is(':animated') ){    //判断UL是否正在处于动画
                          if( $scope.page == page_count ){  //已经到最后一个版面了,如果再向后，必须跳转到第一个版面。
						$v_show.animate({ left : '0px'}, 'slow'); //通过改变left值，跳转到第一个版面
						$scope.page = 1;
						}else{
						$v_show.animate({ left : '-='+v_width }, 'slow');  //通过改变left值，达到每次换一个版面
						$scope.page++;
					 }
				 }
		   });
		    //往前 按钮
		    $('div.lbtn').click(function(){
			     var $parent = $(this).parents('div.numadd');//根据当前点击元素获取到父元素
				 var $v_show = $parent.find('#adimg'); //匹配UL
				 var $v_content = $parent.find('.addcontactimg'); //匹配UL外围的DIV元素
				 var v_width = $v_content.width();
				 var len = $v_show.find('li').length;//计算LI个数
				 var page_count = Math.ceil(len / i) ;   //只要不是整数，就往大的方向取最小的整数
				 if( !$v_show.is(':animated') ){    //判断UL是否正在处于动画
				 	 if( $scope.page == 1 ){  //已经到第一个版面了,如果再向前，必须跳转到最后一个版面。
						$v_show.animate({ left : '-='+v_width*(page_count-1) }, 'slow');
						$scope.page = page_count;
					}else{
						$v_show.animate({ left : '+='+v_width }, 'slow');
						$scope.page--;
					}
				}
		    });
		});

        $scope.fullTextSearch = function () {
            $timeout(function(){
                //全文搜索
                $scope.searchResult = $filter('fullTextSearch')(ContactHandler.getContacts(), GroupHandler.getGroups(), $scope.searchCondition);
                setTimeout(function(){ 
                	$('div.searchResult').textSearch($scope.searchCondition);
                	$scope.resetChatBoxStyle(0);
                    if(($scope.searchCondition=='' || $scope.searchCondition==null)&&$scope.showAddress==true){
                    	$scope.resetChatBoxStyle(1);
                    }
                }, 200);
            }, 500);
        };


        /**
          *   group
          *
          **/

        $scope.groupSearch = function(){
            $timeout(function() {
                $scope.searchGroupAddressResult = $filter('searchContacts')(ContactHandler.getContacts(), $scope.groupCondition);
                setTimeout(function(){ $('div.searchResult').textSearch($scope.groupCondition);}, 200);
            }, 500);
        }
        $scope.groupPersons = [];
        
        //点击创建群聊
		$scope.clickCreateGroupBut = function($event){
			$scope.page = 1;    //重置添加人员滚动面板
			$('div.numadd').find('#adimg').animate({ left : '0px'}, 'slow'); //匹配UL设置为版面1
			//$scope.$apply();
			$scope.showMaskBox = true;
			$scope.showAddParticipantsBox = true;
            $scope.groupContactIderfiers = [];
            $scope.groupPersons = [];
        };
        
        $scope.addGroupPerson = function(identifier,event){
            if($scope.groupContactIderfiers.contains(identifier)){
                return;
            }
        	if($scope.groupPersons.contains(identifier)){
                $scope.groupPersons.remove(identifier);
        	}else{
                $scope.groupPersons.push(identifier);
            }
        };

        $scope.delGroupPerson = function (identifier, event) {
            if ($scope.groupPersons.contains(identifier)) {
                $scope.groupPersons.remove(identifier);
                $('#span_' + identifier).attr('class','check');
                $('#span_search_' + identifier).attr('class','check');
            }
        };

        $scope.createGroup = function(){
        	var data = {};
            var userNames = [$rootScope.user.identifier];
            $scope.groupCondition = '';
            if($scope.showAddGroupContactBox){//是否为单人聊天添加人员
                userNames.push($rootScope.currentChatObj.identifier);
            }
            //发起聊天，选中单人聊天时 应为单人聊天
            if(($scope.showAddParticipantsBox && $scope.groupPersons.length == 1)
                || ($scope.groupPersons.length == 2 && $scope.groupPersons.contains($rootScope.user.identifier))){
                var contact = {};
                if (($scope.groupPersons[0] == $rootScope.user.identifier) && $scope.groupPersons.length == 2) {
                    contact = ContactHandler.getContact($scope.groupPersons[1]);
                }else{
                    contact = ContactHandler.getContact($scope.groupPersons[0]);
                }
            	$scope.confirmChat(contact);
            	$scope.showAddParticipantsBox = false;
            	return;
            }
            //过滤重复人员
            angular.forEach($scope.groupPersons, function(identifier){
               if(!userNames.contains(identifier)){
                   userNames.push(identifier);
               }
            });
            var names = [];
            angular.forEach($filter('toContacts')(userNames),function(contact){
                names.push(contact.name);
        	});
            data.usernames = userNames.join(',');
            data.name = names.join(',');

            if(data.name.length > 50){//默认群名不能超过50个字符
                data.name = data.name.substring(0,47).concat('...');
            }

            GroupHandler.createGroupPromise(data).then(function(data){//success
                $scope.showMaskBox = false;
                $scope.showAddParticipantsBox = false;
                $scope.showAddGroupContactBox = false;
                $scope.groupCondition='';
                $scope.groupPersons = [];
                $scope.groupContactIderfiers = [];
                $scope.groupChat(data);
            }, function(errorMessage){//error
                swal({title : errorMessage, timer : 2000, showConfirmButton : false});
                return;
            });
        };

        $scope.saveGroupContact = function(){
            if($rootScope.isGroup){//群聊添加人员
                var paramData = {};
                paramData.addContactNames = $scope.groupPersons.join(',');
                paramData.groupIdentifier = $rootScope.currentChatObj.identifier;
                GroupHandler.addContactPromise(paramData).then(function(data){
                    GroupHandler.queryGroupPromise({'groupUid': $rootScope.currentChatObj.identifier}).then(function(group){
                        GroupHandler.saveGroup(group);
                        $rootScope.currentChatObj = GroupHandler.getGroupByIdentifier($rootScope.currentChatObj.identifier);
                        ChatHandler.updateChat({'identifier': $rootScope.currentChatObj.identifier, 'userCount' : $rootScope.currentChatObj.userCount});
                        ContactHandler.getContactsByGroupPromise($rootScope.currentChatObj.identifier, false);
                    }, function(errorMsg){
                        swal({title : errorMsg, timer : 2000, showConfirmButton : false});
                        return;
                    });
                    for(var i = 0; i < $scope.groupPersons.length; i++){
                        var identifier = $scope.groupPersons[i];
                        $scope.currentContacts.push(ContactHandler.getContact(identifier));
                    }
                    $scope.groupContactIderfiers = $scope.groupContactIderfiers.concat($scope.groupPersons);
                    //提示消息
                    var message = {};
                    message.commType = 52;//加人
                    message.groupId = $rootScope.currentChatObj.identifier;
                    message.optUser = $rootScope.user.identifier;
                    message.to = $rootScope.currentChatObj.identifier;
                    message.users = $scope.groupPersons;
                    MessageView.groupTipMessageFormat(message);
                    $rootScope.messages.push(message);

                    $scope.showMaskBox = false;
                    $scope.showAddGroupContactBox = false;
                    $scope.groupCondition='';
                    $scope.groupPersons = [];
                },function(errorMessage){
                    swal({title : errorMessage, timer : 2000, showConfirmButton : false});
                    return;
                });
            }else{//单人聊天添加人员
                $scope.createGroup();
            }
        }

        //修改群名
        $scope.updateGroupName = function(){
            if($scope.groupName == null || $scope.groupName == ''){
                swal({title : '请输入群聊名称！', timer : 2000, showConfirmButton : false});
                return;
            }
            if($scope.groupName.length > 32){
                swal({title : '群聊名称长度不能超过32个字符！', timer : 2000, showConfirmButton : false});
                return;
            }
            var paramData = {};
            paramData.groupIdentifier = $rootScope.currentChatObj.identifier;
            paramData.groupName = $scope.groupName;
            GroupHandler.updateGroupPromise(paramData).then(function(data){
                $rootScope.currentChatObj.name = $scope.groupName;
                swal({title : '修改成功！', timer : 2000, showConfirmButton : false});
                ChatHandler.updateChat({identifier : paramData.groupIdentifier, name : paramData.groupName});
            }, function(errorMessage){
                swal({title : errorMessage, timer : 2000, showConfirmButton : false});
                return;
            });
        }

        //联系人退出群组
        $scope.exitGroup = function(contact){
            var paramData = {
                groupIdentifier : $rootScope.currentChatObj.identifier,
                exitContactName : contact.identifier
            };
            GroupHandler.exitGroupPromise(paramData).then(function(data){
                GroupHandler.queryGroupPromise({'groupUid': $rootScope.currentChatObj.identifier}).then(function(group){
                    GroupHandler.saveGroup(group);
                    $rootScope.currentChatObj = GroupHandler.getGroupByIdentifier($rootScope.currentChatObj.identifier);
                    ChatHandler.updateChat({'identifier': $rootScope.currentChatObj.identifier, 'userCount' : $rootScope.currentChatObj.userCount});
                    ContactHandler.getContactsByGroupPromise($rootScope.currentChatObj.identifier, false);
                }, function(errorMsg){
                    swal({title : errorMsg, timer : 2000, showConfirmButton : false});
                    return;
                });
                for(var i = 0; i < $scope.currentContacts.length; i++){
                    var tempContact = $scope.currentContacts[i];
                    if(tempContact.identifier == contact.identifier){
                        $scope.currentContacts.splice(i, 1);
                        break;
                    }
                }
                $scope.groupContactIderfiers.remove(contact.identifier);
                //提示消息
                var message = {};
                message.commType = 53;//踢人
                message.groupId = $rootScope.currentChatObj.identifier;
                message.optUser = $rootScope.user.identifier;
                message.to = $rootScope.currentChatObj.identifier;
                message.users = [contact.identifier];
                MessageView.groupTipMessageFormat(message);
                $rootScope.messages.push(message);
            }, function(errorMessage){
                swal({title : errorMessage, timer : 2000, showConfirmButton : false});
                return;
            });
        }

	}]);
